package my.jwds.p166;

import java.math.BigDecimal;
import java.util.HashMap;

public class FractionToDecimal {

    public static void main(String[] args) {
        FractionToDecimal obj = new FractionToDecimal();
        System.out.println(obj.fractionToDecimal(1,3));
    }

    public String fractionToDecimal(int numerator, int denominator) {
        if (numerator == 0)return "0";
        StringBuilder res = new StringBuilder();
        long n = numerator,d = denominator;
        if ((n <0 && d>0 || n >0 &&d<0)){
            res.append('-');
        }
        n = Math.abs(n);
        d = Math.abs(d);
        res.append(n/d);
        long mod = n%d;
        HashMap<Long,Integer> mods = new HashMap();
        StringBuilder decimals = new StringBuilder();
        int index = 0;
        while(mod != 0 && index != 10000){
            if (mods.containsKey(mod)){
                int splitIndex = mods.get(mod);
                res.append(".");
                res.append(decimals.substring(0,splitIndex));
                res.append("(");
                res.append(decimals.substring(splitIndex));
                res.append(")");
                break;
            }
            mods.put(mod,index++);
            mod*=10;
            if (mod < d){
                decimals.append('0');
            }else{
                decimals.append(mod/d);
                mod%=d;
            }
        }
        if ((mod == 0 || index == 10000)&& decimals.length() != 0){
            res.append(".");
            res.append(decimals);
        }
        return res.toString();
    }
    public String fractionToDecimal1(int numerator, int denominator) {
        BigDecimal bigNumerator = new BigDecimal(numerator);
        BigDecimal bigDenominator = new BigDecimal(denominator);
        String number = bigNumerator.divide(bigDenominator,10000, BigDecimal.ROUND_DOWN).toString();
        number = clearZero(number);
        String res = number;
        if (number.length() > 10000){
            int pointIndex = number.indexOf(".");
            String decimals = number.substring(pointIndex+1);
            char temp = decimals.charAt(0);
            for (int i = 1; i <= 5000; i++) {
                if (temp == decimals.charAt(i) && decimals.substring(0,i).equals(decimals.substring(i,i+i))){
                    res = number.substring(0,pointIndex+1)+"("+decimals.substring(0,i)+")";
                    break;
                }
            }
        }
        return res;
    }

    public String clearZero(String number){
        for (int i = number.length()-1; i >= 0 ; i--) {
            if (number.charAt(i) != '0' && number.charAt(i) != '.'){
                number = number.substring(0,i+1);
                break;
            }
        }
        return number;
    }
}
